<template>
  <el-dialog
      v-model="dialogVisible"
      title="添加用户信息"
      width="30%"
      center
      @close="closeDialog(false)"
  >
    <el-form ref="addFormRef" :model="userForm" :rules="userRules" label-width="120px" class="demo-dynamic" status-icon>
      <el-form-item label="用户名" prop="user_name">
        <el-input v-model="userForm.user_name" placeholder="Enter UserName...">

        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="userForm.password" type="password" placeholder="Enter Email...">

        </el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email" placeholder="Enter Password...">

        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="() => {
          closeDialog(false);
        }">取消</el-button>
        <el-button type="primary" @click="submitAdd()"
        >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {reactive, ref, toRefs} from "vue";
import axios from "axios";
//邮箱规则校验
function userCheckMail(){
  const checkMail = (rule, value, cb) => {
    const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
     if (regEmail.test(value)){
       return cb();
     }
     cb(new Error("请输入合法的邮箱"));
  }
  return {
    checkMail,
  };
}
//用户信息的添加
function useAdd(addFormRef, emit){
  const submitAdd = () => {
    addFormRef.value.validate((valid) => {
      if(valid){
        // addFormRef.value.model 获取表单的数据
        axios.post("/api/user", addFormRef.value.model).then((res) => {
          emit('onCloseDialog', false, res);
          addFormRef.value.resetFields();
        })
      }
    })
  };
  return {
    submitAdd
  }
}
export default {
  name: "AddUser",
  props: {
    dialogVisible:Boolean
  },
  emits: ["onCloseDialog"],
  setup(props, {emit}) {
    const state=reactive({
      dialogVisible:props.dialogVisible,
      userForm:{
        user_name:"",
        password:"",
        email:""
      }
    });
    const userRules = {
      user_name: [{required: true, message: 'Please input house_name', trigger: 'blur',}],
      password: [{required: true, message: 'Please input address', trigger: 'blur',}],
      email: [
        {required: true, message: 'Please input correct email', trigger: 'blur'},
        {validator:userCheckMail().checkMail, trigger: 'blur'}
      ],
    }
    const addFormRef = ref();
    const closeDialog = (visible) => {
      addFormRef.value.resetFields();
      emit('onCloseDialog', visible)
    }
    return {
      ...toRefs(state),
      userRules,
      closeDialog,
      addFormRef,
      ...useAdd(addFormRef, emit)
    }
  }
}
</script>

<style scoped>

</style>